<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 1000px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
    >
      <template style="display: flex">
        <el-form-item label="合同名称" prop="contractName">
          <el-input
            v-model="formData.contractName"
            placeholder="请输入合同名称"
            class="!w-280px"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input
            v-model="formData.contractNo"
            placeholder="合同编号自动生成"
            disabled
            class="!w-280px"
          />
        </el-form-item>
      </template>
      <div style="display: none">
        <el-form-item label="合同状态" prop="contractStatus">
          <el-radio-group v-model="formData.contractStatus" :disabled="!isEdit || disabled">
            <el-radio
              v-for="dict in getStrDictOptions(DICT_TYPE.CONTRACT_STATUS)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="甲方名称" prop="partyA">
          <el-input
            v-model="formData.partyA"
            placeholder="请输入甲方名称"
            class="!w-280px"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="乙方名称" prop="partyB">
          <el-input
            v-model="formData.partyB"
            placeholder="请输入乙方名称"
            class="!w-280px"
            :disabled="disabled"
          />
        </el-form-item>
      </div>
      <div style="display: flex">
        <!-- <el-form-item label="合同类型" prop="contractType">
          <el-select v-model="formData.contractType" placeholder="请选择合同类型" class="!w-280px">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.CONTRACT_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="合同税率" prop="contractTaxRate">
          <el-input
            type="number"
            v-model="formData.contractTaxRate"
            placeholder="请输入合同税率"
            class="!w-280px"
            :disabled="disabled"
          >
            <template #append>%</template></el-input
          >
        </el-form-item>
      </div>

      <div style="display: flex">
        <el-form-item label="合同总金额(含税)" prop="contractAmountInclTax">
          <el-input
            type="number"
            v-model="formData.contractAmountInclTax"
            placeholder="请输入合同总金额(含税)"
            class="!w-280px"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="合同总金额(不含税)" prop="contractAmountExclTax">
          <el-input
            type="number"
            v-model="formData.contractAmountExclTax"
            placeholder="请输入合同总金额(不含税)"
            class="!w-280px"
            :disabled="disabled"
          />
        </el-form-item>
      </div>

      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleChange">
        <el-tab-pane
          :label="item.label"
          :name="item.value"
          v-for="item in tabsList"
          :key="item.value"
        />
      </el-tabs>
      <!-- 详细表单 -->
      <ContentWrap v-if="activeName == 1">
        <div style="display: flex">
          <el-form-item label="合同责任部门" prop="contractDepartmentId">
            <el-select
              v-model="formData.contractDepartmentId"
              placeholder="请选择合同责任部门"
              clearable
              filterable
              :disabled="disabled"
              class="!w-280px"
            >
              <el-option
                v-for="dict in deptList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="合同责任人" prop="contractResponsiblePersonId">
            <el-select
              v-model="formData.contractResponsiblePersonId"
              placeholder="请选择合同责任人"
              clearable
              :disabled="disabled"
              filterable
              class="!w-280px"
            >
              <el-option
                v-for="dict in userList"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div style="display: flex">
          <el-form-item label="责任人联系电话" prop="responsiblePersonPhone">
            <el-input
              v-model="formData.responsiblePersonPhone"
              placeholder="请输入责任人联系电话"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
          <el-form-item label="甲方签署人员" prop="partyAManager">
            <el-input
              v-model="formData.partyAManager"
              placeholder="请输入甲方签署人员"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
        </div>
        <div style="display: flex">
          <el-form-item label="乙方公司名称" prop="partyBDepartment">
            <el-input
              v-model="formData.partyBDepartment"
              placeholder="请输入乙方公司名称"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
          <el-form-item label="乙方责任人" prop="partyBResponsiblePerson">
            <el-input
              v-model="formData.partyBResponsiblePerson"
              placeholder="请输入乙方责任人"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
        </div>
        <div style="display: flex">
          <el-form-item label="乙方联系人电话" prop="partyBManagerPhone">
            <el-input
              v-model="formData.partyBManagerPhone"
              placeholder="请输入乙方联系人电话"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
          <el-form-item label="乙方签署人员" prop="partyBManager">
            <el-input
              v-model="formData.partyBManager"
              placeholder="请输入乙方签署人员"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
        </div>
        <div style="display: flex">
          <el-form-item label="乙方联系人微信" prop="partyBManagerWx">
            <el-input
              v-model="formData.partyBManagerWx"
              placeholder="请输入乙方联系人微信"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
          <el-form-item label="乙方联系人邮箱" prop="partyBManagerEmail">
            <el-input
              v-model="formData.partyBManagerEmail"
              placeholder="请输入乙方联系人邮箱"
              class="!w-280px"
              :disabled="disabled"
            />
          </el-form-item>
        </div>
        <el-form-item label="付款信息" v-if="isEdit && detailRespList">
          <div>
            <div
              v-for="item in detailRespList"
              :key="item.id"
              style="display: flex; align-items: center; margin-bottom: 10px"
            >
              <div
                style="
                  width: 100px;
                  height: 65px;
                  margin-right: 10px;
                  line-height: 65px;
                  text-align: center;
                  background-color: #c5c5c5;
                "
              >
                第{{ item.period }}期
              </div>
              <div
                style="
                  display: flex;
                  width: 620px;
                  height: 65px;
                  flex-wrap: wrap;
                  justify-content: space-around;
                "
              >
                <div
                  style="
                    display: flex;
                    width: 30%;
                    height: 30px;
                    margin-bottom: 5px;
                    align-items: center;
                  "
                >
                  <div style="width: 80px; text-align: right">应付金额：</div>
                  <el-input v-model="item.planPaymentAmount" disabled class="!w-100px" />
                </div>
                <div
                  style="
                    display: flex;
                    width: 36%;
                    height: 30px;
                    margin-bottom: 5px;
                    align-items: center;
                  "
                >
                  <div style="width: 100px; text-align: right">计划付款时间：</div>
                  <el-input
                    :value="formatDate(item.planDate, 'YYYY-MM-DD')"
                    disabled
                    class="!w-120px"
                  />
                </div>
                <div
                  style="
                    display: flex;
                    width: 33%;
                    height: 30px;
                    margin-bottom: 5px;
                    align-items: center;
                  "
                >
                  <div style="width: 100px; text-align: right">对应合同比例：</div>
                  <el-input v-model="item.planPaymentRatio" disabled class="!w-100px">
                    <template #append>%</template>
                  </el-input>
                </div>
                <div style="display: flex; width: 30%; height: 30px; align-items: center">
                  <div style="width: 80px; text-align: right">实付金额：</div>
                  <el-input v-model="item.actualAmount" disabled class="!w-100px" />
                </div>
                <div style="display: flex; width: 36%; height: 30px; align-items: center">
                  <div style="width: 100px; text-align: right">实际付款时间：</div>
                  <el-input
                    :value="formatDate(item.actualDate, 'YYYY-MM-DD')"
                    disabled
                    class="!w-120px"
                  />
                </div>
                <div style="display: flex; width: 33%; height: 30px; align-items: center">
                  <div style="width: 100px; text-align: right">付款类型：</div>
                  <el-select
                    v-model="item.paymentType"
                    placeholder="选择付款类型"
                    clearable
                    disabled
                    suffix-icon=""
                    class="!w-100px"
                  >
                    <el-option
                      v-for="dict in getStrDictOptions(DICT_TYPE.PAYMENT_TYPE)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <template style="display: flex">
          <el-form-item label="紧急程度" prop="urgencyLevel">
            <el-select
              v-model="formData.urgencyLevel"
              placeholder="请选择紧急程度"
              class="!w-280px"
              :disabled="disabled"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.URGENCY_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="保密程度" prop="confidentialityLevel">
            <el-select
              v-model="formData.confidentialityLevel"
              placeholder="请选择保密程度"
              class="!w-280px"
              :disabled="disabled"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CONFIDENTIALITY_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="签订时间" prop="signingDate">
          <el-date-picker
            v-model="formData.signingDate"
            type="date"
            value-format="x"
            :disabled="disabled"
            placeholder="选择签订时间"
            class="!w-280px"
          />
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker
              v-model="formData.effectiveDate"
              type="date"
              :disabled="disabled"
              value-format="x"
              placeholder="选择生效日期"
              class="!w-280px"
            />
          </el-form-item>
          <el-form-item label="终止日期" prop="expirationDate">
            <el-date-picker
              v-model="formData.expirationDate"
              type="date"
              value-format="x"
              :disabled="disabled"
              placeholder="选择终止日期"
              class="!w-280px"
            />
          </el-form-item>
        </div>

        <el-form-item label="摘要内容" prop="contractSummary">
          <Editor v-model="formData.contractSummary" height="150px" :readonly="disabled" />
        </el-form-item>

        <el-form-item label="合同关键页图片" v-if="isEdit">
          <UploadImgsV2
            :disabled="disabled"
            v-model:modelValue="contractKeyImages"
            :file-list="contractKeyImages"
            @file-uploaded="(file) => handleCommonUpload(file, 'KEY_IMAGE')"
            @file-removed="(file) => handleCommonRemove(file, 'KEY_IMAGE')"
          />
        </el-form-item>
      </ContentWrap>

      <!-- 附件 -->
      <ContentWrap v-if="activeName == 3">
        <UploadFileV2
          v-if="isEdit"
          :title="'上传附件'"
          :disabled="disabled"
          v-model:modelValue="attachmentList"
          @file-uploaded="(file) => handleCommonUpload(file, 'ATTACHMENT')"
          @file-removed="(file) => handleCommonRemove(file, 'ATTACHMENT')"
        />
        <el-table :data="attachmentList" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="序号" type="index" fixed="left" width="60" />
          <el-table-column label="附件名称" prop="fileName" />
          <el-table-column label="附件格式" prop="fileFormat" />
          <el-table-column label="创建人" prop="creator" />
          <el-table-column label="上传时间" prop="createTime">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="previewFile('update', scope.row.previewUrl)"
                v-hasPermi="['erp:contract:update']"
              >
                预览
              </el-button>
              <el-button
                link
                type="primary"
                @click="downloadFile(scope.row.downloadUrl)"
                v-hasPermi="['erp:contract:update']"
              >
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
      <!-- 相关合同 -->
      <ContentWrap v-if="activeName == 4">
        <UploadFileV2
          v-if="isEdit"
          :title="'上传相关合同'"
          :disabled="disabled"
          v-model:modelValue="relatedContractList"
          @file-uploaded="(file) => handleCommonUpload(file, 'RELATED_CONTRACT')"
          @file-removed="(file) => handleCommonRemove(file, 'RELATED_CONTRACT')"
        />
        <el-table :data="relatedContractList" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="序号" type="index" fixed="left" width="60" />
          <el-table-column label="相关关联合同名称" prop="fileName" />
          <el-table-column label="合同创建人" prop="creator" />
          <el-table-column label="合同创建成功时间" prop="createTime">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="previewFile('update', scope.row.previewUrl)"
                v-hasPermi="['erp:contract:update']"
              >
                在线预览
              </el-button>
              <!-- <el-button
                link
                type="primary"
                @click="handleJump('update', scope.row)"
                v-hasPermi="['erp:contract:update']"
              >
                跳转查看
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>

      <!-- 合同执行进度 -->
      <ContentWrap v-if="activeName == 5">
        <template v-if="isEdit">
          <div style="display: flex; align-items: center; justify-content: center; margin: 20px 0">
            <span>合同总金额：</span>
            <el-input disabled class="!w-280px" />
          </div>
          <div
            v-for="item in detailRespList"
            :key="item.id"
            style="display: flex; align-items: center; justify-content: center; margin-bottom: 10px"
          >
            <div
              style="
                width: 70px;
                height: 30px;
                margin-right: 10px;
                line-height: 30px;
                text-align: center;
                background-color: #a6a6a6;
              "
              >第{{ item.period }}期</div
            >
            <div style="display: flex; align-items: center; justify-content: center">
              <div style="display: flex; align-items: center; justify-content: center"
                ><div style="width: 100px; text-align: right">已付金额：</div>
                <el-input v-model="item.actualAmount" disabled
              /></div>
              <div style="display: flex; align-items: center; justify-content: center"
                ><div style="width: 180px; text-align: right">剩余总金额：</div>
                <el-input
                  :value="Number(item.planPaymentAmount) - Number(item.actualAmount)"
                  disabled
              /></div>
            </div>
          </div>
        </template>
      </ContentWrap>

      <!-- 盖章打印 -->
      <ContentWrap v-if="activeName == 6">
        <template v-for="item in allImageUrls" :key="item">
          <el-image
            style="width: 200px; height: 200px; margin-right: 10px"
            :src="item"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="allImageUrls"
            show-progress
            :initial-index="0"
            fit="cover"
          />
        </template>
        <div style="text-align: center" v-if="isEdit">
          <el-button
            @click="handlePrint"
            :disabled="printLoading || allImageUrls.length === 0"
            type="primary"
          >
            {{ printLoading ? '打印准备中...' : '唤起网页打印' }}
          </el-button></div
        >
        <div id="printContainer" class="print-container"></div>
      </ContentWrap>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm('submit')" type="primary" :disabled="formLoading"
        >确定提交</el-button
      >
    </template>
  </Dialog>

  <!-- 预览弹框 -->
  <Dialog v-model="previewDialogVisible" title="预览" width="700">
    <div class="flex justify-around">
      <IFrame :src="previewUrl" />
    </div>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ContractApi, ContractVO } from '@/api/erp/contract'
import { ContractFileRelationApi } from '@/api/erp/contractfilerelation'
import { getSimpleAllUserList } from '@/api/system/user' // 角色
import { getSimpleAllDeptList } from '@/api/system/dept' // 部门
import { formatDate } from '@/utils/formatTime.js'
defineOptions({ name: 'ContractForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref<Partial<ContractVO>>({
  id: undefined,
  contractName: undefined,
  contractNo: undefined,
  contractStatus: undefined,
  signingDate: undefined,
  partyA: undefined,
  partyB: undefined,
  contractTaxRate: undefined,
  contractAmountInclTax: undefined,
  contractAmountExclTax: undefined,
  contractDepartment: undefined,
  contractDepartmentId: undefined,
  contractResponsiblePerson: undefined,
  contractResponsiblePersonId: undefined,
  responsiblePersonPhone: undefined,
  partyAManager: undefined,
  partyBDepartment: undefined,
  partyBResponsiblePerson: undefined,
  partyBManagerPhone: undefined,
  partyBManager: undefined,
  partyBManagerWx: undefined,
  partyBManagerEmail: undefined,
  urgencyLevel: undefined,
  confidentialityLevel: undefined,
  effectiveDate: undefined,
  expirationDate: undefined,
  contractSummary: ''
})

/** 表单校验规则 */
const formRules = reactive({
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  contractStatus: [{ required: true, message: '请选择合同状态', trigger: 'change' }],
  signingDate: [{ required: true, message: '请选择签订时间', trigger: 'change' }],
  partyA: [{ required: true, message: '甲方名称不能为空', trigger: 'blur' }],
  partyB: [{ required: true, message: '乙方名称不能为空', trigger: 'blur' }],
  // contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  contractTaxRate: [
    { required: true, message: '请输入合同税率', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value >= 0 && value <= 100) callback()
        else callback(new Error('税率必须在0-100之间'))
      },
      trigger: 'blur'
    }
  ],
  contractAmountInclTax: [
    { required: true, message: '请输入含税总金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value >= 0) callback()
        else callback(new Error('金额不能为负数'))
      },
      trigger: 'blur'
    }
  ],
  contractAmountExclTax: [
    { required: true, message: '请输入不含税总金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value >= 0) callback()
        else callback(new Error('金额不能为负数'))
      },
      trigger: 'blur'
    }
  ],
  contractDepartmentId: [{ required: true, message: '请选择合同责任部门', trigger: 'blur' }],
  contractResponsiblePersonId: [{ required: true, message: '请输入合同责任人', trigger: 'blur' }],
  responsiblePersonPhone: [
    { required: true, message: '请输入责任人联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  partyAManager: [{ required: true, message: '请输入甲方签署人员', trigger: 'blur' }],
  partyBDepartment: [{ required: true, message: '请输入乙方公司名称', trigger: 'blur' }],
  partyBResponsiblePerson: [{ required: true, message: '请输入乙方责任人', trigger: 'blur' }],
  partyBManagerPhone: [
    { required: true, message: '请输入乙方联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  partyBManager: [{ required: true, message: '请输入乙方签署人员', trigger: 'blur' }],
  partyBManagerWx: [{ required: true, message: '请输入乙方联系人微信', trigger: 'blur' }],
  partyBManagerEmail: [
    { required: true, message: '请输入乙方联系人邮箱', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ],
  urgencyLevel: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
  confidentialityLevel: [{ required: true, message: '请选择保密程度', trigger: 'change' }],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (formData.value.signingDate && value) {
          if (Number(value) >= Number(formData.value.signingDate)) callback()
          else callback(new Error('生效日期不能早于签订日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  expirationDate: [
    { required: true, message: '请选择终止日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (formData.value.effectiveDate && value) {
          if (Number(value) >= Number(formData.value.effectiveDate)) callback()
          else callback(new Error('终止日期不能早于生效日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  contractSummary: [{ max: 500, message: '摘要内容不能超过500个字符', trigger: 'blur' }]
})

/** 获取人员列表 */
const userList = ref([])
const getUserList = async () => {
  try {
    const data = await getSimpleAllUserList()
    userList.value = data
  } catch (err) {
    console.error('获取用户列表失败:', err)
  }
}

/** 获取部门列表 */
const deptList = ref([])
const getDeptList = async () => {
  try {
    const data = await getSimpleAllDeptList()
    deptList.value = data
  } catch (err) {
    console.error('获取用户列表失败:', err)
  }
}

/** 打开表单 */
const disabled = computed(() => formType.value === 'detail')
const formRef = ref()
const isEdit = ref(false)
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  getDeptList()
  getUserList()
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    isEdit.value = true
    formLoading.value = true
    try {
      formData.value = await ContractApi.getContract(id)
      if (!formData.value.contractSummary) {
        formData.value.contractSummary = ''
      }
      detailRespList.value = formData.value.paymentPlanRespVO?.detailRespVOS
      await initContractRelatedFiles()
    } finally {
      formLoading.value = false
    }
  } else {
    isEdit.value = false
    formData.value.contractStatus = 'UN_AUDIT'
  }
}
defineExpose({ open })

/** tabs配置 */
const activeName = ref(1)
const tabsList = reactive([
  { value: 1, label: '详细表单' },
  // { value: 2, label: '批办过程' },
  { value: 3, label: '附件' },
  { value: 4, label: '相关合同' },
  // { value: 5, label: '合同执行进度' },
  { value: 6, label: '盖章申请' }
])
const handleChange = () => {
  console.log(activeName.value)
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async (action: 'draft' | 'submit') => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      status: action === 'draft' ? 'DRAFT' : 'SUBMITTED'
    } as ContractVO
    if (formType.value === 'create') {
      await ContractApi.createContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractApi.updateContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractName: undefined,
    contractNo: undefined,
    contractStatus: undefined,
    signingDate: undefined,
    partyA: undefined,
    partyB: undefined,
    contractTaxRate: undefined,
    contractAmountInclTax: undefined,
    contractAmountExclTax: undefined,
    contractDepartment: undefined,
    contractDepartmentId: undefined,
    contractResponsiblePerson: undefined,
    contractResponsiblePersonId: undefined,
    responsiblePersonPhone: undefined,
    partyAManager: undefined,
    partyBDepartment: undefined,
    partyBResponsiblePerson: undefined,
    partyBManagerPhone: undefined,
    partyBManager: undefined,
    partyBManagerWx: undefined,
    partyBManagerEmail: undefined,
    urgencyLevel: undefined,
    confidentialityLevel: undefined,
    effectiveDate: undefined,
    expirationDate: undefined,
    contractSummary: ''
  }
  activeName.value = 1
  contractKeyImages.value = []
  attachmentList.value = []
  relatedContractList.value = []
  formRef.value?.resetFields()
}

/** 关联文件 */
const detailRespList = ref([]) // 付款信息
const contractKeyImages = ref([]) // 关联图片
const allImageUrls = computed(() => {
  return contractKeyImages.value.map((item) => item.url)
})
const attachmentList = ref([]) // 关联附件
const relatedContractList = ref([]) // 关联附件

// 初始化：获取合同已关联的文件列表
const initContractRelatedFiles = async () => {
  if (!formData.value.id) return
  try {
    //  获取关联图片
    const data = await ContractFileRelationApi.getContractFileRelationPage({
      contractId: formData.value.id,
      fileCategory: 'KEY_IMAGE'
    })
    // 获取关联附件
    const attachmentData = await ContractFileRelationApi.getContractFileRelationPage({
      contractId: formData.value.id,
      fileCategory: 'ATTACHMENT'
    })
    attachmentList.value = attachmentData.list
    // 获取相关合同关联
    const RELATEDCONTRACTData = await ContractFileRelationApi.getContractFileRelationPage({
      contractId: formData.value.id,
      fileCategory: 'RELATED_CONTRACT'
    })
    // 分别赋值
    contractKeyImages.value = data.list.map((item) => ({
      id: item.infraFileId, // 文件ID
      url: item.previewUrl, //预览URL
      name: item.fileName, // 文件名
      type: item.fileFormat // 文件格式
    }))
    attachmentList.value = attachmentData.list
    relatedContractList.value = RELATEDCONTRACTData.list
  } catch (error) {
    ElMessage.error('获取合同关联文件失败')
    console.error('初始化失败：', error)
  }
}

//  上传
const handleCommonUpload = async (file: { data: Object }, type) => {
  contractKeyImages.value = []
  if (!formData.value.id) {
    ElMessage.warning('请先选择合同')
    return
  }
  try {
    await ContractFileRelationApi.createContractFileRelation({
      contractId: formData.value.id,
      infraFileId: file.data.id, // 关联文件表ID
      fileCategory: type,
      fileName: file.data.name,
      fileFormat: file.data.type, // 后端返回的fileFormat
      previewUrl: file.data.url, // 后端返回的previewUrl
      downloadUrl: file.data.url,
      fileRemark: type
    })
    ElMessage.success('文件已关联到合同')
    initContractRelatedFiles()
  } catch (error) {
    ElMessage.error('文件关联失败')
    console.error('关联失败：', error)
  }
}
// 删除
const handleCommonRemove = async (file: { data: Object }, type) => {
  if (!formData.value.id) return
  try {
    // 查询该文件与合同的关联记录（获取关联ID）
    const data = await ContractFileRelationApi.getContractFileRelationPage({
      contractId: formData.value.id,
      infraFileId: file.id,
      fileCategory: type
    })
    // 删除关联记录（使用关联记录的id）
    if (data.list.length > 0) {
      const relationId = data.list[0].id // 关联记录的主键ID
      await ContractFileRelationApi.deleteContractFileRelation(relationId)
      ElMessage.success('文件已从合同移除')
      // 刷新列表
      initContractRelatedFiles()
    }
  } catch (error) {
    ElMessage.error('移除关联失败')
    console.error('删除失败：', error)
  }
}

/** 文件预览 */
const previewDialogVisible = ref(false)
const previewUrl = ref('')
const previewFile = (type, url) => {
  const previewPath = url.replace('/get/', '/preview/')
  previewDialogVisible.value = true
  previewUrl.value = previewPath
}
/** 文件下载 */
const downloadFile = (url: string) => {
  window.open(url, '_self')
}
/** 跳转查看 */
const handleJump = (id: number) => {
  console.log('跳转查看合同:', id)
}

/** 打印相关状态  */
const printLoading = ref(false)
const isPrinting = ref(false)
const printTimer = ref<NodeJS.Timeout | null>(null)
/** 唤起打印 */
const handlePrint = () => {
  const imageUrls = allImageUrls.value
  if (imageUrls.length === 0) {
    ElMessage.warning('没有可打印的图片')
    return
  }
  if (isPrinting.value || printLoading.value) {
    ElMessage.info('正在准备打印，请稍后...')
    return
  }

  // 开启加载状态
  printLoading.value = true
  isPrinting.value = true
  const loadingMessage = ElMessage.info({
    message: '正在准备打印内容，请稍候...',
    duration: 0,
    showClose: false
  })

  // 创建iframe
  const iframe = document.createElement('iframe')
  iframe.style.cssText = `
    position: absolute; 
    top: -9999px; 
    left: -9999px;
    width: 100%; 
    height: auto; 
    border: none;
    opacity: 0;
  `
  document.body.appendChild(iframe)

  // 获取iframe的内容窗口
  const iframeWindow = iframe.contentWindow
  console.log(iframeWindow)

  // 状态重置函数
  const resetPrintState = () => {
    // 清除超时定时器
    if (printTimer.value) {
      clearTimeout(printTimer.value)
      printTimer.value = null
    }

    // 重置状态
    printLoading.value = false
    isPrinting.value = false
    loadingMessage.close()

    // 移除iframe
    setTimeout(() => {
      if (document.body.contains(iframe)) {
        document.body.removeChild(iframe)
      }
    }, 100)

    // 移除事件监听
    if (iframeWindow) {
      iframeWindow.removeEventListener('afterprint', handleAfterPrint)
      iframeWindow.removeEventListener('beforeprint', handleBeforePrint)
    }
  }

  // 打印前事件
  const handleBeforePrint = () => {
    console.log('开始打印流程')
  }

  // 打印后事件（无论成功或取消都会触发）
  const handleAfterPrint = () => {
    console.log('打印流程结束（确认或取消）')
    resetPrintState()
  }

  // 绑定事件监听到iframe的contentWindow
  if (iframeWindow) {
    iframeWindow.addEventListener('beforeprint', handleBeforePrint)
    iframeWindow.addEventListener('afterprint', handleAfterPrint)
  }

  // 添加超时兜底机制（5分钟未操作自动重置）
  printTimer.value = setTimeout(() => {
    console.log('打印超时，自动重置状态')
    ElMessage.warning('打印超时，请重试')
    resetPrintState()
  }, 5 * 60 * 1000)

  // 构建打印内容
  const printHtml = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <style>
        @media print {
          @page { margin: 1.5cm; }
          body { margin: 0; padding: 0; }
          img {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            page-break-inside: avoid;
          }
        }
      </style>
    </head>
    <body>
      ${imageUrls
        .map(
          (url) => `
        <img 
          src="${url}" 
          alt="合同图片" 
          onload="this.style.opacity=1" 
          style="opacity:0;transition:opacity 0.3s"
          onerror="console.error('图片加载失败:', '${url}')"
        >
      `
        )
        .join('')}
    </body>
    </html>
  `

  // 加载打印内容
  iframe.srcdoc = printHtml
  iframe.onload = () => {
    // 检查图片加载情况
    const checkImagesLoaded = () => {
      const imgElements = iframe.contentDocument?.querySelectorAll('img')
      if (!imgElements || imgElements.length === 0) {
        return true
      }
      return Array.from(imgElements).every((img) => img.complete)
    }

    // 等待图片加载完成再打印
    const interval = setInterval(() => {
      if (checkImagesLoaded()) {
        clearInterval(interval)
        setTimeout(() => {
          try {
            if (iframeWindow) {
              iframeWindow.print()
              resetPrintState()
            }
          } catch (error) {
            ElMessage.error('打印过程出错：' + (error as Error).message)
            resetPrintState()
          }
        }, 300)
      }
    }, 100)
  }

  iframe.onerror = (error) => {
    ElMessage.error('打印内容加载失败，请重试')
    console.error('iframe加载错误：', error)
    resetPrintState()
  }
}
</script>
